import {Component, OnInit} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../my-service/util.service";
import {TrainingService} from "../../my-service/training.service";
import {Training} from "../Training";
import {Router, ActivatedRoute} from "@angular/router";

@Component({
  selector: 'start-root',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.css'],
})
export class StartComponent implements OnInit {
  projectName='et';
  showChange = false;//改变查看方式
  isEdit = false;//是否处于编辑状态
  deleteIsEdit = false;//回收站是否处于编辑状态
  addTest = false;//添加测试
  userGuid = null;
  trainingList = []; //获取所有训练的原始数据
  deleteTrainingList = [];//已经删除的所有的训练的原始数据
  trainingOfClassGroups = [];//根据班级进行分组后的数据
  classNames = [];//存放的是班级的名称
  bilendTrainingList = [];//存放匿名测试
  showBilendTrainingList=[];//展示的匿名测试
  modifyTraining = null;//修改的测试
  trainingByMonthGroups = [[]];//根据月份分组以后的数据,二维数组默认只存前面2个月的
  monthList = [];//存放显示月份的数组
  lastYear: number;//存放当前页面显示第一个月的年份
  lastMonth: number;//存放当前页面显示第一个月的月份
  modifyTrainingIndex = [];//保存按月修改的index;
  deleteStatus:boolean;
  // 根据训练列表查询邀请码
  getCodeByTrainingList(trainingList){
    let nowTime = this.utilServe.getCurrentTime();
    trainingList.forEach(training=>{
        this.trainingService.getCodeBytrainingId(training.id).then(res=>{
          if(res.status==1){
              training.inviteCode=res.code;
            training.inviteCodeGuid=res.guid;
              if(res.EndTime>=nowTime){
                training.codeEnd=false;
              }
            }
        })
    })
  }
  //获取所有未删除的训练
  getTrainingList(): any {
    this.trainingService.getTrainingList(this.userGuid, 1).then(res => {
      if (res.status == 1 && res.data[0]) {
        res.data.forEach(val => {
          this.trainingList.push(new Training(val.PK_TrainingGuid, val.TrainingName, val.Description, this.userGuid, null, true,val.CreateTime, null, null,val.FK_ClassGuid))
        });
        this.getTrainingStus(this.trainingList);
        this.getCodeByTrainingList(this.trainingList);
        this.trainingOfClassGroup(this.trainingList);
        this.trainingList.forEach(training => {
          //获取班级名称
          if (training.classGuid && training.classGuid !== 'null') {
            this.trainingService.getClassInfo(training.classGuid).then(res => {
              if (res.status == 1) {
                training.className = res.data[0].ClassName
              }
            })
          }
        });
      }
    })
  }

  /*获取删除的训练*/
  getDleteList(): any {
    this.trainingService.getTrainingList(this.userGuid, 0).then(res => {
      if (res.status == 1 && res.data[0]) {
        res.data.forEach(val => {
          this.deleteTrainingList.push(new Training(val.PK_TrainingGuid, val.TrainingName, val.Description, this.userGuid, null, false, val.CreateTime, null,null, val.FK_ClassGuid, ))
        });
        this.getCodeByTrainingList(this.deleteTrainingList);
        this.getTrainingStus(this.deleteTrainingList);
      }
      /*获取删除的班级名称*/
      this.deleteTrainingList.forEach(training => {
        if (training.classGuid && training.classGuid !== 'null') {
          this.trainingService.getClassInfo(training.classGuid).then(res => {
            if (res.status == 1) {
              training.className = res.data[0].ClassName;
            }
          })
        }
      })
    })
  }

  /*根据班级进行分组*/
  trainingOfClassGroup(trainings) {
    let classGuids = [['null']];//二维数组，数组的第一个位置存放的是班级的GUID
    /*提取班级Guid*/
    trainings.forEach(training => {
      let index = 0;
      classGuids.forEach(val => {
        if (training.classGuid !== val[0]) {
          index += 1;
        }
        if (index == classGuids.length) {
          classGuids.push([training.classGuid]);
        }
      })
    });
    /*把每一个二维数组放进去*/
    classGuids.forEach(val => {
      trainings.forEach(training => {
        if (val[0] == training.classGuid) {
          val.push(training);
        }
      })
    });
    /*获取匿名测试*/
    this.bilendTrainingList = classGuids.splice(0, 1);
    /*去除匿名测试中的Null*/
    this.bilendTrainingList.forEach(val => {
      val.splice(0, 1);
    });
    //只显示4个，匿名测试
    if(this.bilendTrainingList[0].length>4){
      this.showBilendTrainingList=this.bilendTrainingList[0].splice(0,4);
    }else {
      this.showBilendTrainingList=this.bilendTrainingList[0];
    }
    /*获取班级信息*/
    let classNameIndex = 0; //防止异步导致班级名称同分组不对应
    classGuids.forEach(val => {
      this.getClassInfo(val[0], classNameIndex);
      /*把GUID给删除了*/
      val.splice(0, 1);
      classNameIndex++
    });
    this.trainingOfClassGroups = classGuids;
    //只显示前面4个；
    this.trainingOfClassGroups.forEach(val => {
      val = val.splice(4);
    })
  }

  /*根据班级Guid获取班级信息*/
  getClassInfo(guid, i) {
    if (!guid || guid == 'null') {
      return
    } else {
      this.trainingService.getClassInfo(guid).then(res => {
        if (res.status == 1) {
          this.classNames[i] = res.data[0].ClassName;
        }
      })
    }
  }

  /*获取参加训练的人数*/
  getTrainingStus(trainingList) {
    trainingList.forEach(training => {
      this.trainingService.getAnswerCardByTrainingId(training.id).then(res => {
        if (res.status == 1) {
          training.studentNum = res.data.length;
        }
      })
    })
  }

  constructor(private message: NzMessageService,
              private utilServe: UtilService,
              private trainingService: TrainingService,
              private  route: Router,
              private  routerInfo: ActivatedRoute,) {
    this.bilendTrainingList[0] = [];
  }

  ngOnInit() {
    this.utilServe.getUserInfo().then(res => {
      this.userGuid = res.userGuid;//获取用户的guid
      this.getTrainingList();
      this.getDleteList();
    })
  }
//关闭添加页面
  onCloseAdd(training) {
    this.addTest = false;
    /*是否有新增测试*/
    if (training.id) {
      //判断新的测试是属于匿名还是非匿名
      if (training.classGuid && training.classGuid !== 'null') {
        //判断是否是修改的测试
        if (training.isModify) {
          for (let i = 0; i < this.trainingList.length; i++) {
            if (training.id == this.trainingList[i].id) {
              this.trainingList.splice(i, 1);
              this.trainingList.push(training);
              break;
            }
          }
          //  如果是按照月份显示修改的
          if (this.modifyTrainingIndex[0]) {
            this.trainingByMonthGroups[this.modifyTrainingIndex[0]][this.modifyTrainingIndex[1]] = training;
            this.modifyTrainingIndex = []; //修改完成，清空记录的索引
          }
        } else {
          this.trainingList.push(training); //新增的
          this.trainingByMonthGroups[0].push(training);//新增的推入当月
        }
        //重新排序
        this.trainingOfClassGroup(this.trainingList);
      } else {
        if (training.isModify) {
          //修改的匿名测试
          for (let i = 0; i < this.bilendTrainingList[0].length; i++) {
            if (training.id = this.bilendTrainingList[0][i].id) {
              this.bilendTrainingList[0].splice(i, 1);
              this.bilendTrainingList[0].unshift(training);
            }
          }
        } else {
          //新增的匿名测试
          this.bilendTrainingList[0].push(training);
          if(this.bilendTrainingList[0].length>4){
            this.showBilendTrainingList=this.bilendTrainingList[0].splice(0,4);
          }else {
            this.showBilendTrainingList=this.bilendTrainingList[0];
          }
          this.trainingByMonthGroups[0].unshift(training);
        }
      }
    }
    this.modifyTraining=null
  }

  /*删除指定Guid的班级训练*/
  deleteTraining(training, className, i, j) {
    this.utilServe.comfirm(`您确认要删除${training.name}嘛？`, () => {
      this.trainingService.deleteInviteCode(training.inviteCodeGuid).then(res=>{});
      this.trainingService.deleteTraining(training.id).then(res => {
        if (res.status == 1) {
          this.message.success(`删除${training.name}成功`);
          training.className = className;
          /*在原有数组中移除*/
          this.trainingOfClassGroups[i].splice(j, 1);
          training.state = false;
          training.codeEnd=true;
          training.inviteCode=null;
          /*如果班级中不存在测试了则把班级删了*/
          if (!this.trainingOfClassGroups[i][0]) {
            this.trainingOfClassGroups.splice(i, 1);
            this.classNames.splice(i, 1);
          }
          //从初始数据中删除
          for (let i = 0; i < this.trainingList.length; i++) {
            if (training.id == this.trainingList[i].id) {
              this.trainingList.splice(i, 1);
              break;
            }
          }
          /*推入删除数组中*/
          this.deleteTrainingList.push(training);
        }
      })
    });
  }

  /*删除匿名训练*/
  deleteTrainingByBlind(training, i) {
    this.utilServe.comfirm(`您确认要删除${training.name}嘛`, () => {
      this.trainingService.deleteInviteCode(training.inviteCodeGuid).then(res=>{});
      this.trainingService.deleteTraining(training.id).then(res => {
        if (res.status == 1) {
          this.message.success((`删除${training.name}成功`));
          /*从匿名测试中移除*/
          this.bilendTrainingList[0].splice(i, 1);
          training.state = false;
          training.codeEnd=true;
          training.inviteCode=null;
          /*推入删除数组中*/
          this.deleteTrainingList.push(training);
        }
      })
    })
  }

  /*恢复训练*/
  recoverTraining(training, i) {
    this.utilServe.comfirm(`您确认要恢复${training.name}嘛?`, () => {
      if (training.classGuid && training.classGuid !== 'null') {
        //  非匿名测试
        this.trainingService.recoverTraining(training.id).then(res => {
          if (res.status == 1) {
            this.message.success(`恢复${training.name}成功`);
            training.state = true;
            //从删除数组中删除
            this.deleteTrainingList.splice(i, 1);
            //推入初始数组中
            this.trainingList.push(training);
            //重新按照班级排序
            this.trainingOfClassGroup(this.trainingList);
          }
        })
      } else {
        //匿名测试
        this.trainingService.recoverTraining(training.id).then(res => {
          if (res.status == 1) {
            this.message.success(`恢复${training.name}成功`);
            training.state = true;
            //从删除数组中删除
            this.deleteTrainingList.splice(i, 1);
            //推入匿名数组中
            this.bilendTrainingList[0].push(training);
          }
        })
      }
    })
  }

  /*修改训练*/
  modifyByTraining(training) {
    training.isModify = true;
    this.addTest = training.isModify;
    this.modifyTraining = training;
  }

  /*将训练根据月份来进行分组*/
  trainingByMonthGroup(trainings, year, month) {
    let monthList = [];
    let firstTime = this.utilServe.getDateTimeOfFirstDay(year, month);//获取每月第一天的时间戳
    let lastTime = this.utilServe.getDateTimeOfLastDay(year, month);//获取每月最后一天的时间戳
    trainings.forEach(training => {
      if (training.createTime >= firstTime && training.createTime <= lastTime) {
        monthList.push(training);
      }
    });
    return monthList;
  }

  /*改变查看方式时对数据按月份进行分组*/
  showChangByMonth() {
    this.showChange = !this.showChange;
    if (this.showChange) {
      //按照月份查看，默认获取2个月的;
      this.trainingByMonthGroups = [];//清空之前按月分组的训练
      this.monthList = [];
      let date = new Date();
      let currentYear = date.getFullYear();
      let currentMonth = date.getMonth() + 1;
      let lastYear, lastMonth;
      if (currentMonth == 1) {
        lastYear = currentYear - 1;
        lastMonth = 12;
      } else {
        lastYear = currentYear;
        lastMonth = currentMonth - 1;
      }
      //获取当前显示的月份
      this.monthList.push(currentMonth);
      this.monthList.push(lastMonth);
      //获取当前显示第一个月的月份
      this.lastYear = lastYear;
      this.lastMonth = lastMonth;
      //获取当前2个月的训练
      let currentMonthTrainingList = this.trainingByMonthGroup(this.trainingList, currentYear, currentMonth);
      let lastMonthTrainingList = this.trainingByMonthGroup(this.trainingList, lastYear, lastMonth);
      this.trainingByMonthGroups.push(currentMonthTrainingList);
      this.trainingByMonthGroups.push(lastMonthTrainingList);
    }
  }

  /*点击自动多获取一个月的*/
  getLastMonth() {
    let month, year;
    if (this.lastMonth == 1) {
      month = 12;
      year = this.lastYear - 1;
    } else {
      month = this.lastMonth - 1;
    }
    let monthTrainings = this.trainingByMonthGroup(this.trainingList, year, month);//获取当前月份分组的数据
    this.trainingByMonthGroups.push(monthTrainings);
    this.monthList.push(month);
    //改变第一个月的值
    this.lastYear = year;
    this.lastMonth = month;
  }

  /*去到班级测试详情页*/
  jumpMinuteByClass(classID, className) {
    this.route.navigate(['../minute', {classID, className}], {relativeTo: this.routerInfo});
  }

  /*按月份显示的修改*/
  modifyTrainingByMonth(training, i, j) {
    this.modifyTrainingIndex = [i, j];
    training.isModify = true;
    this.addTest = training.isModify;
    this.modifyTraining = training;
  }

  /*按月份显示的删除*/
  deleteTrainingByMonth(training, i, j) {
    this.utilServe.comfirm(`您确认要删除${training.name}嘛?`, () => {
      this.trainingService.deleteTraining(training.id).then(res => {
        if (res.status == 1) {
          this.message.success(`您删除${training.name}成功`);
          this.trainingByMonthGroups[i].splice(j, 1);//从月份数组中移除
          //从原始数组中移除
          for (let i = 0; i < this.trainingList.length; i++) {
            if (this.trainingList[i].id == training.id) {
              this.trainingList.splice(i, 1);
              //从新按照班级分组
              this.trainingOfClassGroup(this.trainingList);
              break;
            }
          }
        } else {
          this.message.error(`您删除${training}失败,请稍后再试`);
        }
      })
    })
  }

//跳转到某个测试详情页面
  jumpRoster(training) {
    if (!this.isEdit) {
      this.route.navigate(['../roster', {
        ID: training.id,
        className: training.className,
        classID: training.classGuid
      }], {relativeTo: this.routerInfo});
    }
  }
  // 创建邀请码
  createCode(event,training){
    //阻止事件冒泡
    event.stopPropagation();
    let endTime = new Date();
    if(training.classGuid!=='null'){
      this.trainingService.getClassInfo(training.classGuid).then(res => {
        if (res.status == 1) {
          training.className = res.data[0].ClassName;
          endTime.setMonth(endTime.getMonth() + 6); //设置结束时间为6个月以后
          let LibQuery=`;className=${training.className};classID=${training.classGuid}`;
          let data={
            projectName:this.projectName,
            guid:training.id,
            FK_ClassGuid:training.classGuid,
            endTime,
            LibQuery
          };
          this.trainingService.createCode(data).then(res=>{
            if(res.status==1){
              training.inviteCode = res.code;
              training.codeEnd=false;
              this.message.success('邀请码生成成功');
            }else {
              this.message.error('邀请码生成失败,请重试');
            }
          })
        }
      });
    }else {
      endTime.setMonth(endTime.getMonth() + 6); //设置结束时间为6个月以后
      let LibQuery=`;className=null;classID=null`;
      let data={
        projectName:this.projectName,
        guid:training.id,
        FK_ClassGuid:training.classGuid,
        endTime,
        LibQuery
      };
      this.trainingService.createCode(data).then(res=>{
        if(res.status==1){
          training.inviteCode = res.code;
          training.codeEnd=false;
          this.message.success('邀请码生成成功');
        }else {
          this.message.error('邀请码生成失败,请重试');
        }
      })
    }

  }
}

